package com.pet.comment.service.impl;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.pet.comment.service.ApCommentReplyService;
import com.pet.comment.feign.ApUserFeign;
import com.pet.common.exception.LeadNewsException;
import com.pet.model.comment.dtos.ApCommentReplyVo;
import com.pet.model.comment.dtos.CommentRepayDto;
import com.pet.model.comment.dtos.CommentReplyLikeDto;
import com.pet.model.comment.dtos.CommentReplySaveDto;
import com.pet.model.comment.pojos.ApComment;
import com.pet.model.comment.pojos.ApCommentReply;
import com.pet.model.comment.pojos.ApCommentReplyLike;
import com.pet.model.common.dtos.ResponseResult;
import com.pet.model.common.enums.AppHttpCodeEnum;
import com.pet.model.user.pojos.ApUser;
import com.pet.utils.common.BeanHelper;
import com.pet.utils.threadlocal.ThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ApCommentReplyServiceImpl implements ApCommentReplyService {

    @Autowired
    private ApUserFeign apUserFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ResponseResult saveCommentReply(CommentReplySaveDto dto) {
        //1.判断用户是否登录
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.判断评论内容长度不超过140字符
        if(StringUtils.isNotEmpty(dto.getCommentId())&&dto.getCommentId().length()>140){
            throw new LeadNewsException(400,"评论内容长度不能超过140个字");
        }

        try {
            //3.保存评论回复数据
            //查询当前用户信息
            apUser= apUserFeign.findOne(apUser.getId()).getData();

            ApCommentReply apCommentReply = new ApCommentReply();
            apCommentReply.setAuthorId(apUser.getId());
            apCommentReply.setAuthorName(apUser.getName());
            apCommentReply.setCommentId(dto.getCommentId());
            apCommentReply.setContent(dto.getContent());
            apCommentReply.setLikes(0);
            apCommentReply.setCreatedTime(new Date());

            mongoTemplate.save(apCommentReply);
            //修改回复的评论的回复数+1
            Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
            Update update = new Update();
            update.inc("reply");

            mongoTemplate.updateMulti(query,update, ApComment.class);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadNewsException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    @Override
    public ResponseResult<List> loadCommentReply(CommentRepayDto dto) {
        if(dto.getMinDate()==null)dto.setMinDate(new Date());
        //1.先根据条件（查询条件+分页+排序）查询评论数据
        //1）封装条件
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        //2）分页 排序   先按照评论点赞数倒序，再按照创建时间倒序
        query.limit(10);
        query.with(Sort.by(Sort.Direction.DESC,"createdTime"));
        //3）查询数据
        List<ApCommentReply> replyList = mongoTemplate.find(query, ApCommentReply.class);
        //2.如果当前用户没有登录，直接返回查询结果即可
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            return ResponseResult.okResult(replyList);
        }
        //3.如果当前用户已登录，判断当前用户对哪些评论点赞过，对点赞过的评论添加operation为0的属性
        //1）根据用户ID和评论ID查询评论点赞记录
        List<String> idList = replyList.stream().map(ApCommentReply::getId).collect(Collectors.toList());
        Query likeQuery = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentReplyId").in(idList));
        List<ApCommentReplyLike> likeList = mongoTemplate.find(likeQuery, ApCommentReplyLike.class);
        //2）遍历commentList
        List<ApCommentReplyVo> apCommentReplyVoList = new ArrayList<>();
        replyList.forEach(comment -> {
            //3）找出commentList中每个评论的id是否和  点赞记录列表的评论ID 相同的记录
           /* for(ApCommentLike like:likeList){
                if(like.getCommentId().equals(comment.getId())){

                }
            }*/

            //拷贝数据
            ApCommentReplyVo apCommentReplyVo = BeanHelper.copyProperties(comment, ApCommentReplyVo.class);
            long count = likeList.stream().filter(apCommentReplyLike -> apCommentReplyLike.getCommentReplyId().equals(comment.getId())).count();
            if(count>0){
                //4）给上一步找出来的评论对象添加operation=0属性
                apCommentReplyVo.setOperation(0);
            }
            apCommentReplyVoList.add(apCommentReplyVo);
        });
        return ResponseResult.okResult(apCommentReplyVoList);
    }

    @Override
    public ResponseResult<Map<String, Object>> likeCommentReply(CommentReplyLikeDto dto) {
        //1.判断用户是否登录
        ApUser apUser = (ApUser) ThreadLocalUtils.get();
        if(apUser==null){
            throw new LeadNewsException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.判断是否存在当前评论的点赞数据，再判断是否点赞还是取消点赞
        //查询当前用户对当前评论点赞记录
        Query query = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentReplyId").is(dto.getCommentReplyId()));
        List<ApCommentReplyLike> commentReplyLikes = mongoTemplate.find(query, ApCommentReplyLike.class);
        if(CollectionUtils.isEmpty(commentReplyLikes)&&dto.getOperation().equals(0)){
            //2.1 点赞操作，新增评论点赞数据，更新评论的likes+1

            //新增评论点赞记录
            ApCommentReplyLike apCommentReplyLike = new ApCommentReplyLike();
            apCommentReplyLike.setAuthorId(apUser.getId());
            apCommentReplyLike.setCommentReplyId(dto.getCommentReplyId());
            apCommentReplyLike.setOperation(0);
            mongoTemplate.save(apCommentReplyLike);
            //更新回复的likes+1
            Query commentQuery= Query.query(Criteria.where("_id").is(dto.getCommentReplyId()));
            Update update = new Update();
            update.inc("likes");
            mongoTemplate.updateMulti(commentQuery,update,ApCommentReply.class);
        }else {
            //2.2 取消点赞操作，删除评论点赞数据，更新评论的likes-1

            //删除评论点赞记录
            mongoTemplate.remove(query,ApCommentReplyLike.class);
            //更新回复的likes-1
            Query commentQuery= Query.query(Criteria.where("_id").is(dto.getCommentReplyId()));
            Update update = new Update();
            update.inc("likes",-1);
            mongoTemplate.updateMulti(commentQuery,update,ApCommentReply.class);
        }
        //查询最新回复的点赞数
        ApCommentReply apCommentReply = mongoTemplate.findById(dto.getCommentReplyId(), ApCommentReply.class);
        Map<String, Object> map = new HashMap<>();
        map.put("likes",apCommentReply.getLikes());
        return ResponseResult.okResult(map);
    }
}
